package com.point.business.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.point.business.database.managers.UsersManager;
import com.point.business.database.model.User;
import com.point.business.util.Role;
import com.point.business.util.UTFUtil;
import com.point.business.util.UserNotFoundException;

/**
 * Servlet implementation class LoginServlet
 */

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		UTFUtil.utf8(request, response);
		try {
			UsersManager.getInstance().testConnection();
			User user = UsersManager.getInstance().login(
					request.getParameter("username"),
					request.getParameter("password"));
			if (user == null) {
				response.sendRedirect(request.getContextPath()
						+ "/error.jsp?errorMessage=User not found");
			} else {
				request.getSession().setAttribute("user", user);
				if (user.getRole() == Role.ADMIN) {
					response.sendRedirect(request.getContextPath()
							+ "/admin/admin.jsp");
				} else {
					response.sendRedirect(request.getContextPath()
							+ "/user/user.jsp");
				}
			}
		} catch (UserNotFoundException e) {
			response.sendRedirect(request.getContextPath()
					+ "/error.jsp?errorMessage=" + e.getMessage());
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getParameter("logout") != null) {
			request.getSession().removeAttribute("user");
			response.sendRedirect(request.getContextPath() + "/index.jsp");
		}
	}
}
